package com.example.controller;


import com.example.bean.ApiResult;
import com.example.bean.Book;
import com.example.service.BookService;
import com.example.utils.ApiResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/book")
@CrossOrigin
public class BookController {

    @Autowired
    private BookService bookService;

    // 根据图书id查询图书信息
    @GetMapping("/selectById/{bookId}")
    public ApiResult selectBookById(@PathVariable String bookId){
        Book res = bookService.selectBookById(bookId);
        if (res != null) {
            return ApiResultHandler.buildApiResult(200, "根据图书Id查询", res);
        } else {
            return ApiResultHandler.buildApiResult(400, "无此图书信息", res);
        }
    }

    @GetMapping("/selectAll")
    public ApiResult selectAll() {
        List<Book> res = bookService.selectBook();
        return ApiResultHandler.buildApiResult(200, "根据图书Id查询", res);
    }

    // 根据图书名字查询图书信息
    @GetMapping("/selectByName/{bookName}")
    public ApiResult selectBookByName(@PathVariable String bookName) {
        List<Book> res = bookService.selectBookByName(bookName);
        if (res != null && !res.isEmpty()) {
            return ApiResultHandler.buildApiResult(200, "根据图书名字查询", res);
        } else {
            return ApiResultHandler.buildApiResult(400, "无此图书信息", res);
        }
    }

    // 根据多个条件查询图书信息
    @GetMapping("/selectByCondition")
    public ApiResult selectBook() {
        List<Book> res = bookService.selectBook();
        if (res != null && !res.isEmpty()) {
            return ApiResultHandler.buildApiResult(200, "多条件查询", res);
        } else {
            return ApiResultHandler.buildApiResult(400, "无此图书信息", res);
        }
    }

    // 添加图书信息到数据库中
    @PostMapping("/insert")
    public ApiResult insertBook(@RequestBody Book book) {
        int res = bookService.insertBook(book);
        if (res != 0) {
            return ApiResultHandler.buildApiResult(200, "添加图书成功", res);
        } else {
            return ApiResultHandler.buildApiResult(400, "添加图书失败",res);
        }
    }

    // 根据图书id删除图书信息
    @DeleteMapping("/delete/{bookId}")
    public ApiResult deleteBook(@PathVariable String bookId) {
        int res = bookService.deleteBook(bookId);
        if (res != 0) {
            return ApiResultHandler.buildApiResult(200, "删除图书成功", res);
        } else {
            return ApiResultHandler.buildApiResult(400, "删除图书失败",res);
        }
    }

    // 更新指定图书的信息
    @PutMapping("/update")
    public ApiResult updateBook(@RequestBody Book book) {
        int res = bookService.updateBook(book);
        if (res != 0) {
            return ApiResultHandler.buildApiResult(200, "更新图书信息成功", res);
        } else {
            return ApiResultHandler.buildApiResult(400, "更新图书信息失败", res);
        }
    }
}
